import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

// 导入组件
import login from '@/views/login/login.vue'
import home from '@/views/home/home.vue'
import my from '@/views/home/my/my.vue'
import myInfo from '@/views/home/my/myInfo.vue'
import find from '@/views/home/find/find.vue'

// 导入 store
import store from '@/store/index.js'
// 导入 token
import { getLocal } from '@/utile/local.js'

// 导入用户信息
import { auInfo } from '@/api/userInfo.js'
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/home',
    component: home,
    redirect: '/home/my',
    children: [
      {
        path: '/home/my',
        component: my,
        meta: {
          needLogin: true, //判断这个页面需不需要登录
          needTab: true // 判断需不需要加底部标签
        }
      },
      {
        path: '/home/myInfo',
        component: myInfo,
        meta: {
          needLogin: true //判断这个页面需不需要登录
        }
      },
      {
        path: '/home/find',
        component: find,
        meta: {
          needTab: true // 判断需不需要加底部标签
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 1.需不需要登录
  if (!to.meta.needLogin) {
    next()
  } else {
    if (store.state.isLogin) {
      //2.判断是不是登录成功
      next()
    } else {
      if (getLocal()) {
        //3.判断有没有token 到这一步已经刷新了
        window.console.log('导航', to)
        // 重新保存 调用接口获取用户的信息
        auInfo().then(res => {
          // window.console.log(res)
          store.commit('getUser', res.data.data)
          store.commit('loginStatus', true)
          next()
        })
      } else {
        next('/login?redirect=' + to.fullPath)
      }
    }
  }
})

const routerPath = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPath.call(this, location).catch(e => e)
}
export default router
